<template>
  <div ref="line" :class="className" :style="{height:height,width:width}" ></div>
</template>

<script>
import * as echarts from 'echarts'
import resize from './utils/resize.js'

export default {
  mixins: [resize],
  props: {
    // 类名
    className: {
      type: String,
      default: 'chart'
    },
    // 宽度，可以传递进来，默认100%
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '250px'
    },
    // 是否自适应，默认为true
    autoResize: {
      type: Boolean,
      default: true
    },
    // 渲染折线图的横轴和纵轴的数据
    chartData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler (val) {
        if (this.chart) {
          this.chart.clear()
        }
        this.setOptions(val)
      }
    }
  },
  mounted () {
    // 注意在mounted中调用initChart，且在nextTick函数中执行
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy () {
    if (!this.chart) {
      return
    }

    // 销毁实例
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart () {
      this.chart = echarts.init(this.$refs.line)
      this.setOptions(this.chartData)
    },
    setOptions ({ time = [], data = [] } = {}) {
      this.chart.setOption({
        xAxis: {
          data: time,
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
        },
        legend: {
          //! 这个进气？
          data: ['湿度', '进气']
        },
        series: [{
          name: '湿度',
          itemStyle: {
            normal: {
              color: '#0099ff',
              lineStyle: {
                color: '#0099ff',
                width: 2
              }
            }
          },
          smooth: false,
          type: 'line',
          data: data,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        }]
      })
    }
  }
}
</script>
